// ElMessage, nanoid 已通过自动引入配置

// 请求配置
const defaultConfig = {
  baseURL: import.meta.env.VITE_API_BASE_URL || '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
}

// 请求拦截器
const requestInterceptors = []
// 响应拦截器
const responseInterceptors = []

class Request {
  constructor(config = {}) {
    this.config = { ...defaultConfig, ...config }
    this.controller = new AbortController()
  }

  // 添加请求拦截器
  addRequestInterceptor(fulfilled, rejected) {
    requestInterceptors.push({ fulfilled, rejected })
  }

  // 添加响应拦截器
  addResponseInterceptor(fulfilled, rejected) {
    responseInterceptors.push({ fulfilled, rejected })
  }

  // 处理请求拦截器
  async processRequestInterceptors(config) {
    for (const interceptor of requestInterceptors) {
      try {
        if (interceptor.fulfilled) {
          config = await interceptor.fulfilled(config)
        }
      } catch (error) {
        if (interceptor.rejected) {
          return interceptor.rejected(error)
        }
        throw error
      }
    }
    return config
  }

  // 处理响应拦截器
  async processResponseInterceptors(response) {
    for (const interceptor of responseInterceptors) {
      try {
        if (interceptor.fulfilled) {
          response = await interceptor.fulfilled(response)
        }
      } catch (error) {
        if (interceptor.rejected) {
          return interceptor.rejected(error)
        }
        throw error
      }
    }
    return response
  }

  // 构建完整URL
  buildURL(url) {
    if (url.startsWith('http://') || url.startsWith('https://')) {
      return url
    }
    return `${this.config.baseURL}${url.startsWith('/') ? url : '/' + url}`
  }

  // 处理请求选项
  async buildRequestOptions(config) {
    const { method = 'GET', data, params, headers = {}, ...otherConfig } = config

    // 处理请求拦截器
    const processedConfig = await this.processRequestInterceptors(config)

    const options = {
      method: method.toUpperCase(),
      headers: {
        ...this.config.headers,
        ...headers,
        'X-Request-ID': nanoid()
      },
      signal: this.controller.signal,
      ...otherConfig
    }

    // 处理查询参数
    let url = this.buildURL(processedConfig.url)
    if (params) {
      const searchParams = new URLSearchParams()
      Object.keys(params).forEach(key => {
        if (params[key] !== undefined && params[key] !== null) {
          searchParams.append(key, params[key])
        }
      })
      url += (url.includes('?') ? '&' : '?') + searchParams.toString()
    }

    // 处理请求体
    if (data && ['POST', 'PUT', 'PATCH'].includes(options.method)) {
      if (data instanceof FormData) {
        delete options.headers['Content-Type']
        options.body = data
      } else if (typeof data === 'object') {
        options.body = JSON.stringify(data)
      } else {
        options.body = data
      }
    }

    return { url, options }
  }

  // 发起请求
  async request(config) {
    try {
      const { url, options } = await this.buildRequestOptions(config)

      // 设置超时
      const timeoutId = setTimeout(() => {
        this.controller.abort()
      }, this.config.timeout)

      const response = await fetch(url, options)
      clearTimeout(timeoutId)

      // 检查HTTP状态
      if (!response.ok) {
        throw new Error(`HTTP Error: ${response.status} ${response.statusText}`)
      }

      // 解析响应
      const contentType = response.headers.get('content-type')
      let result

      if (contentType && contentType.includes('application/json')) {
        result = await response.json()
      } else if (contentType && contentType.includes('text/')) {
        result = await response.text()
      } else {
        result = await response.blob()
      }

      const processedResponse = {
        data: result,
        status: response.status,
        statusText: response.statusText,
        headers: response.headers,
        config: config
      }

      // 处理响应拦截器
      return await this.processResponseInterceptors(processedResponse)
    } catch (error) {
      if (error.name === 'AbortError') {
        throw new Error('请求超时')
      }

      // 显示错误消息
      ElMessage.error(error.message || '请求失败')
      throw error
    }
  }

  // 取消请求
  cancel(_message = '请求被取消') {
    this.controller.abort()
  }

  // GET请求
  get(url, config = {}) {
    return this.request({ ...config, url, method: 'GET' })
  }

  // POST请求
  post(url, data, config = {}) {
    return this.request({ ...config, url, data, method: 'POST' })
  }

  // PUT请求
  put(url, data, config = {}) {
    return this.request({ ...config, url, data, method: 'PUT' })
  }

  // DELETE请求
  delete(url, config = {}) {
    return this.request({ ...config, url, method: 'DELETE' })
  }

  // PATCH请求
  patch(url, data, config = {}) {
    return this.request({ ...config, url, data, method: 'PATCH' })
  }
}

// 创建默认实例
const request = new Request()

// 添加默认请求拦截器
request.addRequestInterceptor(
  config => {
    // 添加认证token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers = config.headers || {}
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 添加默认响应拦截器
request.addResponseInterceptor(
  response => {
    // 统一处理响应数据
    const result = response.data
    if (result && typeof result === 'object' && 'code' in result) {
      if (result.code === 0 || result.code === 200) {
        return result.data || result
      } else {
        ElMessage.error(result.message || '请求失败')
        throw new Error(result.message || '请求失败')
      }
    }
    return result
  },
  error => {
    // 统一错误处理
    if (error.response?.status === 401) {
      // 未授权，清除token并跳转到登录页
      localStorage.removeItem('token')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export default request
export { Request }
